package cn.jk.service;

import cn.jk.dao.AnimalDao;
import cn.jk.dao.IUserDao;
import cn.jk.dao.UserDao;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

/**
 * 实现ApplicationContextAware可以赋值ApplicationContext
 * 也可以直接Autowired  ApplicationContext
 */
@Service
public class UserService implements ApplicationContextAware {

	private ApplicationContext context;

	@Autowired
	private IUserDao userDao1;

	//可注入为空的写法，或者加@Nullable
	@Autowired
	private Optional<AnimalDao> animalDao;

	//可注入该类型的集合，包括set和list
	@Autowired
	private Map<String, IUserDao> userDaoMap;

	public void query(){
//		System.out.println("query + 测试一下");
		UserDao userDao = (UserDao) context.getBean("userDao");
		userDao.query();
		System.out.println(userDao.hashCode());
	}

	public void queryTest(){
		IUserDao userDao = (IUserDao) context.getBean("user-test");
		userDao.query();
		System.out.println(userDao.hashCode());
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.context = applicationContext;
	}
}
